package com.realbrand.net.realbrandpay.ui.activity.wallet.personer;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.realbrand.net.realbrandpay.APP;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.alipay.AuthResult;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IAuthorized;
import com.realbrand.net.realbrandpay.inter.IGetAuthInfo;
import com.realbrand.net.realbrandpay.inter.IUnbound;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.CheckOutActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.bean.GetAuthCode;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/7/10.
 */

public class BoundPayActivity extends BaseActivity {
    @BindView(R.id.boundpayActivity_toolbar)
    Toolbar boundpayActivityToolbar;
    @BindView(R.id.boundpay_tv_boundAlipayName)
    TextView boundpayTvBoundAlipayName;
    @BindView(R.id.boundpay_tv_boundAlipay)
    TextView boundpayTvBoundAlipay;
    @BindView(R.id.boundpay_tv_boundWXName)
    TextView boundpayTvBoundWXName;
    @BindView(R.id.boundpay_tv_boundWX)
    TextView boundpayTvBoundWX;

    private String userName;

    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        boundpayActivityToolbar.setTitle("");
        boundpayActivityToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(boundpayActivityToolbar);
        boundpayActivityToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(BoundPayActivity.this, AccountActivity.class));
                finish();
            }
        });
        EventBus.getDefault().register(this);
        userName = getIntent().getStringExtra("usreName");
        sharedPreferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);

        String wxName = sharedPreferences.getString("WXName", "");
        if (!"".equals(wxName)) {
            L.d(L.TAG, "授权了");
            boundpayTvBoundWXName.setText(wxName);
            boundpayTvBoundWX.setText("解除绑定");
        } else {
            boundpayTvBoundWXName.setText("");
            boundpayTvBoundWX.setText("去绑定");
        }
        String alipayName = sharedPreferences.getString("alipayName", "");
        if (!"".equals(alipayName)) {
            boundpayTvBoundAlipayName.setText(alipayName);
            boundpayTvBoundAlipay.setText("解除绑定");
        } else {
            boundpayTvBoundAlipay.setText("去绑定");
            boundpayTvBoundAlipayName.setText("");
        }
        setOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.boundpay_layout;
    }

    @Override
    protected void setOnClick() {
        boundpayTvBoundWX.setOnClickListener(this);
        boundpayTvBoundAlipay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.boundpay_tv_boundAlipay:
                if (APP.AlipayIsAuth) {
                    unbundle(userName, 2);
                } else {
                    getAuthInfo(2);
                }
                break;
            case R.id.boundpay_tv_boundWX:
                if (APP.WXIsAuth) {
                    unbundle(userName, 1);
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    String date = sdf.format(new java.util.Date());
                    boundleWX(date);
                }
                break;

        }
    }

    /**
     * 支付宝获取授权所需字符串
     *
     * @param i
     */

    private void getAuthInfo(int i) {
        JSONObject authJson = new JSONObject();
        try {
            authJson.put("SOURCE", "WithdrawActivity");
            authJson.put("CREDENTIALS", "0");
            authJson.put("TERMINAL", "1");
            authJson.put("INDEX", Static.getDay());
            authJson.put("METHOD", "Authorized");
            authJson.put("PaymentMode", i);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, authJson.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IAuthorized iAuthorized = retrofit.create(IAuthorized.class);
            Call<ResponseBody> authorized = iAuthorized.authorized(body);
            authorized.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String string = response.body().string();
                        L.d(L.TAG, "获取授权字符串返回的结果" + string);
                        if (string.equals("")) {
                            Static.toast(BoundPayActivity.this, "网络繁忙");
                        } else {
                            JSONObject jsonObject = new JSONObject(string);
                            JSONArray data = jsonObject.getJSONArray("DATA");
                            String authString = data.getString(0);
                            alipayAuth(authString);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        L.d(L.TAG, "绑定支付宝支付异常" + e.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝授权
     *
     * @param authString
     */
    private void alipayAuth(final String authString) {
        Runnable authRunnable = new Runnable() {
            @Override
            public void run() {
                AuthTask authTask = new AuthTask(BoundPayActivity.this);
                Map<String, String> result = authTask.authV2(authString, true);
                Message msg = new Message();
                msg.what = CheckOutActivity.SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    /**
     * 微信授权
     *
     * @param date
     */
    private void boundleWX(String date) {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = date;
        Constant.wx_api.sendReq(req);
    }


    private void unbundle(String userName, final int i) {
        JSONObject boundJosn = new JSONObject();
        try {
            boundJosn.put("SOURCE", "BoundActivity");
            boundJosn.put("CREDENTIALS", "0");
            boundJosn.put("TERMINAL", "1");
            boundJosn.put("INDEX", Static.getDay());
            boundJosn.put("METHOD", "Unbundled");
            boundJosn.put("PaymentMode", i + "");
            boundJosn.put("UserAccount", userName);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, boundJosn.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IUnbound iUnbound = retrofit.create(IUnbound.class);
            Call<ResponseBody> unbundled = iUnbound.unbundled(body);
            unbundled.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String result = response.body().string();
                        if (result.equals("")) {
                            Static.toast(BoundPayActivity.this, "网络繁忙");
                        } else {
                            L.d(L.TAG, "解绑返回数据" + result);
                            JSONObject resultJson = new JSONObject(result);
                            JSONArray data = resultJson.getJSONArray("DATA");
                            String dataString = data.getString(0);
                            if (dataString.equals("1")) {
                                //解绑成功
                                Message message = new Message();
                                if (i == 1) {
                                    APP.WXIsAuth = false;
                                    message.what = 0005;
                                    mHandler.sendMessage(message);
                                    SharedPreferences.Editor edit = sharedPreferences.edit();
                                    edit.putString("WXName", "");
                                    edit.commit();
                                } else if (i == 2) {
                                    APP.AlipayIsAuth = false;
                                    message.what = 0006;
                                    mHandler.sendMessage(message);
                                    SharedPreferences.Editor edit = sharedPreferences.edit();
                                    edit.putString("alipayName", "");
                                    edit.commit();
                                }
                            } else {
                                Static.toast(BoundPayActivity.this, "网络繁忙,解绑失败");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        L.d(L.TAG, "支付宝解绑异常" + e.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Subscribe          //订阅事件FirstEvent
    public void onEventMainThread(GetAuthCode code) {
        getAuthResult(code.getCode(), 1, userName);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 请求服务器获取授权信息
     *
     * @param code 授权code
     * @param i    哪一种支付方式
     */

    private void getAuthResult(String code, final int i, String userName) {

        try {
            JSONObject getResultjson = new JSONObject();
            getResultjson.put("SOURCE", "WithdrawActivity");
            getResultjson.put("CREDENTIALS", "0");
            getResultjson.put("TERMINAL", "1");
            getResultjson.put("INDEX", Static.getDay());
            getResultjson.put("METHOD", "GetAuthInfo");
            getResultjson.put("PaymentMode", i + "");
            getResultjson.put("AuthCode", code);
            getResultjson.put("UserAccount", userName);
            L.d(L.TAG, "参数" + getResultjson.toString());
            RequestBody body = RequestBody.create(HTTPAPI.JSON, getResultjson.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IGetAuthInfo iGetAuthInfo = retrofit.create(IGetAuthInfo.class);
            Call<ResponseBody> authInfo = iGetAuthInfo.getAuthInfo(body);
            authInfo.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String getAuthInfo = response.body().string();
                        L.d(L.TAG, "获取授权成功返回的结果" + getAuthInfo);
                        if (getAuthInfo.equals("")) {
                            Static.toast(BoundPayActivity.this, "网络繁忙");
                        } else {
                            JSONObject getAuthInfoJson = new JSONObject(getAuthInfo);
                            JSONArray data = getAuthInfoJson.getJSONArray("DATA");
                            if (data.length() == 0) {
                                Static.toast(BoundPayActivity.this, "授权失败");
                            } else {
                                //表示授权成功
                                JSONObject object = data.getJSONObject(0);
                                String name = object.getString("nick_name");
                                Message message = new Message();
                                if (i == 2) {
                                    message.what = CheckOutActivity.CHANGE_UI_ALIPAY;
                                    message.obj = name;
                                    mHandler.sendMessage(message);
                                    APP.AlipayIsAuth = true;
                                    SharedPreferences.Editor edit = sharedPreferences.edit();
                                    edit.putString("alipayName", name);
                                    edit.commit();
                                } else if (i == 1) {
                                    message.what = CheckOutActivity.CHANGE_UI_WX;
                                    message.obj = name;
                                    mHandler.sendMessage(message);
                                    APP.WXIsAuth = true;
                                    SharedPreferences.Editor edit = sharedPreferences.edit();
                                    edit.putString("WXName", name);
                                    edit.commit();
                                }
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        L.d(L.TAG, "异常" + e.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CheckOutActivity.SDK_AUTH_FLAG:
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        //获取授权code
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                try {
                                    sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                        String authCode = authResult.getAuthCode();
                        getAuthResult(authCode, 2, userName);
                    } else {
                        Static.toast(BoundPayActivity.this, "授权失败");
                    }
                    break;
                case CheckOutActivity.CHANGE_UI_ALIPAY:
                    String alipayName = (String) msg.obj;
                    boundpayTvBoundAlipay.setText("解除绑定");
                    boundpayTvBoundAlipayName.setText(alipayName);
                    break;
                case CheckOutActivity.CHANGE_UI_WX:
                    String WXName = (String) msg.obj;
                    boundpayTvBoundWX.setText("解除绑定");
                    boundpayTvBoundWXName.setText(WXName);
                    break;
                case 0005:
                    boundpayTvBoundWX.setText("去绑定");
                    boundpayTvBoundWXName.setText("");
                    break;
                case 0006:
                    boundpayTvBoundAlipay.setText("去绑定");
                    boundpayTvBoundAlipayName.setText("");
                    break;
            }
        }
    };
}
